<template>
  <el-menu class="el-menu-demo" mode="horizontal" :ellipsis="false">
    <el-menu-item>
      <Logo></Logo>
    </el-menu-item>
    <el-menu-item>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item v-for="item in matchedRoutes" :key="item">{{
          item.name
        }}</el-breadcrumb-item>
      </el-breadcrumb>
    </el-menu-item>
    <el-sub-menu>
      <template #title>用户：{{ appUserStore.currentUser.name }}</template>
      <el-menu-item
        @click="userSwitcher = true"
        v-if="appUserStore.currentUser && appUserStore.currentUser.isManager"
        >切换用户</el-menu-item
      >
      <el-menu-item @click="onLogout">登出</el-menu-item>
    </el-sub-menu>
    <el-menu-item>
      <el-avatar
        :size="32"
        class="mr-3"
        src="https://cube.elemecdn.com/0/88/03b0d39583f48206768a7534e55bcpng.png"
      />
    </el-menu-item>
  </el-menu>
  <el-drawer
    v-model="userSwitcher"
    title="I am the title"
    size="400px"
    v-if="appUserStore.currentUser && appUserStore.currentUser.isManager"
    @closed="onReload"
  >
    <template #header>
      <el-text size="large">用户切换</el-text>
    </template>
    <SelectorUser
      :multiple="false"
      :user-selector="userSelector"
      :users="users"
      :index="index"
      v-for="(userSelector, index) in userSelectors"
      :key="index"
      @change="onNodeUserChange"
    />
  </el-drawer>
</template>

<script setup>
import { useAppStore } from "@/stores/app";
import { computed, ref } from "vue";
import { useRouter, useRoute } from "vue-router";
import { useOrganisationUserStore } from "@/stores/organisationUser";
import { useAppUserStore } from "@/stores/appUser";
import SelectorUser from "./../WorkflowDesign/FlowProcesses/SelectorUser.vue";
import Logo from "./Logo.vue";

const organisationUserStore = useOrganisationUserStore();
const appUserStore = useAppUserStore();
const appStore = useAppStore();

const title = computed(() => appStore.pageTitle);
const router = useRouter();

const userSelectors = ref([{}]);
const users = ref([]);
const userSwitcher = ref(false);

const route = useRoute();
const matchedRoutes = computed(() => route.matched);

const onNodeUserChange = (val) => {
  userSelectors.value[val.index] = val.selector;
  users.value = val.users;
  if (val.users.length > 0) {
    const user = val.users[0];
    appUserStore.setCurrentUser({ id: user.id, name: user.name });
  }
};
const onReload = () => {
  location.reload();
};
const onLogout = () => {
  organisationUserStore.logout();
  appUserStore.setAppId("");
  appUserStore.setCurrentUser({ id: "", name: "" });
  router.replace({ path: "/login" });
};
</script>
<style scoped>
.el-menu--horizontal > .el-menu-item:nth-child(2) {
  margin-right: auto;
}
.el-page-header {
  padding: 10px;
}
.el-avatar {
  cursor: pointer;
}
</style>
